#include <QtQml>
#include <signal.h>
#include "app.h"
#include "db/db.h"
#include "coletorpcp.h"

#include <QOpenGLContext>
#include <QOffscreenSurface>
#include <QOpenGLFunctions>

#include "pesagemcontroller.h"
#include "utils/log.h"
#include "utils/conf.h"
#include "utils/pluginutil.h"

void signalHandler(int signal) {
    LOGD("BEGIN");
    switch(signal) {
    case SIGHUP: PluginUtil::reloadTouchPlugin(); break;
    case SIGTERM: APP::clearScreen(); break;
    }
    LOGD("END");
}

int APP::exec(QGuiApplication& app) {
    LOGD("BEGIN");
    qmlRegisterType<ColetorPCP>("ColetorPCP",1,0,"ColetorPCP");
    qmlRegisterType<PesagemController>("ColetorPCP",1,0,"PesagemController");
    qmlRegisterType<Conf>("ColetorPCP",1,0,"Conf");

    signal(SIGHUP, signalHandler);
    signal(SIGTERM, signalHandler);

    qsrand(time(0));

    connect(&app, SIGNAL(aboutToQuit()), SLOT(close()) );
    engine.load(MAIN_VIEW);

    mainWindow = (QWindow*)engine.rootObjects()[0];

    PluginUtil::reloadTouchPlugin();

    Conf conf(CONF_FILE_NAME, 0);
    QString plataforma = conf.get_plataforma();

//    QString departamento = "departamento";
//    QMetaObject::invokeMethod(mainWindow,"start",Q_ARG(QVariant, departamento));

    if(plataforma == "embarcado") {
        mainWindow->showFullScreen();
    } else {
        mainWindow->showMaximized();
    }

    int result = app.exec();

    LOGD("END");
    return result;
}

void APP::close() {
    LOGD("BEGIN");
    LOGD("END");

}

void APP::clearScreen()
{
    LOGD("BEGIN");
    QOpenGLContext ctx;
    ctx.create();
    QOffscreenSurface surface;
    surface.setFormat(ctx.format());
    surface.create();
    ctx.makeCurrent(&surface);
    glClear(GL_COLOR_BUFFER_BIT);
//    ctx.functions()->glClear(GL_COLOR_BUFFER_BIT);
    ctx.swapBuffers(&surface);
    LOGD("END");
}


